/**
 * 文件描述如下：
 * 1. ws_point_cloud_src.js 用于感知点云数据的获取
 * 2. 连接方式为：WebSocket
 * 3. 连接地址为：ws://192.168.3.161:20038/point-cloud-src
 * 4.
 */

import { mainStore } from '../../../store/mainStore.js'
import { sourceArr } from './pageDate.js'
let store, params

const handleWebSocketMessage = (event) => {
  if (store.perceivedEffectStatus == 'pause') return
  const arr = JSON.parse(event.data)?.['batch_images'] ?? []

  // 处理视频数据 显示页面上 无论切换哪个 一定有视频数据
  store.videoData_Json = JSON.parse(JSON.stringify(arr)) ?? []

  const d3Arr = JSON.parse(JSON.stringify(arr))
  store.empyTip = d3Arr.length == 0 ? '当前数组为空' : ''

  // 将数据进行聚合
  store.carData = d3Arr.flatMap((item) => item['perception-objects'] ?? [])

  // 历史数据留存
  store.pcdHistory.push(arr)
  if (store.pcdHistory.length > store.frameNum) {
    store.pcdHistory.shift()
  }
}

export const connectWS_per_eff = (id) => {
  params = sourceArr.find((item) => item.id == id)

  store = mainStore()

  const ip = `ws://${window.location.host}/ws`
  const socket = new WebSocket(ip + params?.path)

  // 开发环境使用
  // const ip = `ws://10.202.1.9:20038`
  // const socket = new WebSocket(`ws://localhost:8099/`)
  // const socket = new WebSocket(ip + '/obstacles-event/avg-fps')

  socket.binaryType = 'arraybuffer' // 处理二进制数据

  socket.onopen = function () {
    console.log(`${params?.dec} ---> 已经连接:`)
  }

  socket.onmessage = handleWebSocketMessage

  socket.onclose = function (event) {
    console.log(`${params?.dec} ---> 断开连接:`)
    console.log('断开原因:', event.code)
  }

  socket.onerror = function (error) {
    console.log('断开原因:', error.code)
  }
  return socket
}

